<template>
  <div class="dashboard">
    <div class="page-header">
      <div>
        <div class="page-header__title">校园运行概览</div>
        <div class="page-header__desc">实时掌握学生、教师、课程与班级数据</div>
      </div>
      <el-button type="primary" @click="loadData" :loading="loading">
        <el-icon><Refresh /></el-icon>
        刷新数据
      </el-button>
    </div>

    <el-row :gutter="16">
      <el-col v-for="card in statCards" :key="card.label" :span="6" :xs="12">
        <el-card class="stat-card">
          <div class="stat-icon" :class="card.type">
            <el-icon><component :is="card.icon" /></el-icon>
          </div>
          <div>
            <div class="stat-value">{{ card.value }}</div>
            <div class="stat-label">{{ card.label }}</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card class="quick-actions">
      <template #header>
        <div class="card-header">
          <span>快捷操作</span>
        </div>
      </template>
      <div class="action-grid">
        <div
          v-for="action in quickActions"
          :key="action.label"
          class="action-item"
          @click="handleAction(action.route)"
        >
          <el-icon><component :is="action.icon" /></el-icon>
          <span>{{ action.label }}</span>
        </div>
      </div>
    </el-card>

    <el-row :gutter="16">
      <el-col :span="12" :xs="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新班级</span>
            </div>
          </template>
          <el-skeleton v-if="loading" :rows="4" animated />
          <el-table v-else :data="recentClasses" border size="small">
            <el-table-column prop="class_name" label="班级" />
            <el-table-column prop="grade" label="年级" width="80" />
            <el-table-column prop="student_count" label="人数" width="80" />
          </el-table>
        </el-card>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>学年学期</span>
            </div>
          </template>
          <el-skeleton v-if="loading" :rows="4" animated />
          <el-timeline v-else>
            <el-timeline-item
              v-for="year in academicYears"
              :key="year.id"
              :timestamp="`${year.start_date} - ${year.end_date}`"
              :type="year.is_current ? 'primary' : 'info'"
            >
              {{ year.year_name }}（{{ semesterMap[year.semester] }}）
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { getStudentList, getTeacherList } from '@/api/users'
import { getClassroomList, getCourseList, getAcademicYearList, getClassList } from '@/api/academic'
import type { ClassItem, AcademicYear } from '@/types/academic'

const router = useRouter()
const loading = ref(false)
const summary = ref({ students: 0, teachers: 0, classrooms: 0, courses: 0, classes: 0 })
const recentClasses = ref<ClassItem[]>([])
const academicYears = ref<AcademicYear[]>([])

const semesterMap: Record<number, string> = {
  1: '秋季学期',
  2: '春季学期'
}

const statCards = computed(() => [
  { label: '学生总数', value: summary.value.students, icon: 'User', type: 'primary' },
  { label: '教师总数', value: summary.value.teachers, icon: 'School', type: 'success' },
  { label: '班级数量', value: summary.value.classes, icon: 'Collection', type: 'warning' },
  { label: '课程数量', value: summary.value.courses, icon: 'Notebook', type: 'info' }
])

const quickActions = [
  { label: '开通账户', icon: 'User', route: '/system/accounts' },
  { label: '角色管理', icon: 'CollectionTag', route: '/system/roles' },
  { label: '学生管理', icon: 'Reading', route: '/users/students' },
  { label: '老师管理', icon: 'Notebook', route: '/users/teachers' },
  { label: '课程管理', icon: 'Memo', route: '/academic/courses' },
  { label: '班级管理', icon: 'Collection', route: '/academic/classes' }
]

const loadData = async () => {
  loading.value = true
  try {
    const [students, teachers, classrooms, courses, classes, years] = await Promise.all([
      getStudentList({ limit: 1 }),
      getTeacherList({ limit: 1 }),
      getClassroomList({ limit: 1 }),
      getCourseList({ limit: 1 }),
      getClassList({ limit: 5 }),
      getAcademicYearList({ limit: 5 })
    ])
    summary.value = {
      students: students.total,
      teachers: teachers.total,
      classrooms: classrooms.total,
      courses: courses.total,
      classes: classes.total
    }
    recentClasses.value = classes.items.slice(0, 5)
    academicYears.value = years.items
  } catch (error: any) {
    ElMessage.error(error?.message || '加载概览数据失败')
  } finally {
    loading.value = false
  }
}

const handleAction = (routePath: string) => {
  router.push(routePath)
}

onMounted(loadData)
</script>

<style scoped lang="scss">
.dashboard {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.stat-card {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);

  .stat-icon {
    width: 48px;
    height: 48px;
    border-radius: var(--radius-md);
    display: flex;
    align-items: center;
    justify-content: center;

    &.primary {
      background: rgba(24, 144, 255, 0.15);
      color: var(--color-primary);
    }
    &.success {
      background: rgba(82, 196, 26, 0.15);
      color: var(--color-success);
    }
    &.warning {
      background: rgba(250, 140, 22, 0.15);
      color: var(--color-warning);
    }
    &.info {
      background: rgba(114, 46, 209, 0.15);
      color: var(--color-info);
    }
  }

  .stat-value {
    font-size: 24px;
    font-weight: 600;
  }

  .stat-label {
    color: var(--text-secondary);
    font-size: 13px;
  }
}

.quick-actions {
  .action-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
    gap: var(--spacing-md);
  }

  .action-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: var(--spacing-md);
    border: 1px dashed var(--border-light);
    border-radius: var(--radius-md);
    cursor: pointer;
    transition: all 0.2s ease;

    .el-icon {
      font-size: 24px;
      margin-bottom: var(--spacing-sm);
    }

    &:hover {
      border-color: var(--color-primary);
      color: var(--color-primary);
      background: rgba(24, 144, 255, 0.05);
    }
  }
}

.card-header {
  font-weight: 600;
}
</style>
